import React from 'react';
import {
  View,
  ScrollView,
  TouchableOpacity,
  Platform,
  Alert,
} from 'react-native';
import {Text, Button, ListItem} from '@rneui/base';
import {
  useDebounceEffect,
  useMap,
  useMount,
  useSafeState,
  useSetState,
  useUpdateEffect,
} from 'ahooks';
import {round} from 'lodash';
import style from './style.less';
import {
  requestMultiple,
  checkMultiple,
  PERMISSIONS,
  RESULTS,
  openSettings,
  request,
} from 'react-native-permissions';
import {useNavigation} from '@react-navigation/native';
import {MapPowerResult, MapPowerName} from '@/config/power';
import {CkPowerWaitMs} from '@/config/common';
import dayjs from 'dayjs';
import {useSelector, useDispatch} from 'react-redux';
import Modal from 'react-native-modal';
import {
  useSafeAreaFrame,
  useSafeAreaInsets,
} from 'react-native-safe-area-context';

export default ({children, clickPowers = [], ...otherProps}) => {
  const frame = useSafeAreaFrame();
  const navigation = useNavigation();
  const appRunState = useSelector(state => state.appRunState.value);

  const [allowPowers, setAllowPowers] = useSafeState([]);
  const [group, setGropu] = useSafeState([]);
  const [unavailablePowers, setUnavailablePowers] = useSafeState([]);
  const [isModalVisible, setModalVisible] = useSafeState(false);

  const setInfo = async () => {
    const newMap = new Map();
    for (const name of new Set(clickPowers)) {
      const key = PERMISSIONS.ANDROID[name] || name;
      newMap.set(key, {name: name});
    }
    const powerList = [...newMap].map(([key]) => key);
    try {
      const statuses = await checkMultiple(powerList);
      for (const [key, powerStr] of Object.entries(statuses)) {
        const oldData = newMap.get(key);
        newMap.set(key, {...oldData, powerStr});
      }

      const getPowersArr = targetValue => {
        const items = [];
        [...newMap].forEach(([, item]) => {
          if (item.powerStr === targetValue) {
            items.push(item);
          }
        });
        return items;
      };

      const allows = getPowersArr(RESULTS.GRANTED);
      setAllowPowers(allows);

      const unavailables = getPowersArr(RESULTS.UNAVAILABLE);
      setUnavailablePowers(unavailables);

      const gArr = [
        // RESULTS.GRANTED,
        RESULTS.LIMITED,
        RESULTS.DENIED,
        RESULTS.BLOCKED,
        // RESULTS.UNAVAILABLE,
      ];
      const rtArr = [];
      gArr.forEach(targetValue => {
        rtArr.push(getPowersArr(targetValue));
      });
      setGropu(rtArr);
    } catch (e) {
      console.log('获取权限异常', e.message);
    }
  };

  useMount(() => {
    setInfo();
  });
  useDebounceEffect(
    () => {
      if (appRunState === 'active') {
        setInfo();
      }
    },
    [appRunState],
    {wait: 0},
  );

  const onPress = async () => {
    if (unavailablePowers.length) {
      let names = unavailablePowers.map(
        item => MapPowerName.get(item.name) || item.name,
      );
      let str = names.join('；');
      Alert.alert(`本机不支持权限：${str}`);
      return;
    }

    const refules = [];
    group.forEach(gRows => {
      gRows.forEach(item => {
        if (item) {
          refules.push(item);
        }
      });
    });
    // console.log('refules', refules, 'group', group, 'clickPowers', clickPowers);
    console.log('refules', refules);
    setModalVisible(true);
  };
  const ModalBox = () => (
    <Modal
      isVisible={isModalVisible}
      onBackdropPress={() => setModalVisible(false)}>
      <View
        style={{
          backgroundColor: '#fff',
          maxHeight: Math.round(frame.height) / 2,
        }}>
        <ScrollView style={{flex: 0}}>
          <Text style={{textAlign: 'center', marginTop: 10}}>
            此功能需要授于以下权限：
          </Text>
          <View style={style.group}>
            {[...allowPowers].map((item, index) => (
              <ListItem key={index} style={{marginTop: 1}}>
                <ListItem.Content>
                  <ListItem.Title>{MapPowerName.get(item.name)}</ListItem.Title>
                  <Text style={style.remark}>{item.name}</Text>
                </ListItem.Content>

                <View>
                  <Text>{MapPowerResult.get(item.powerStr)}</Text>
                  <Text style={style.remark}>{item.powerStr}</Text>
                </View>
              </ListItem>
            ))}
          </View>
          {group.map((gRows, gIndex) => (
            <View key={gIndex} style={style.group}>
              {[...gRows].map((item, index) => (
                <ListItem key={index} style={{marginTop: 1}}>
                  <ListItem.Content>
                    <ListItem.Title>
                      {MapPowerName.get(item.name)}
                    </ListItem.Title>
                    <Text style={style.remark}>{item.name}</Text>
                  </ListItem.Content>
                  <View>
                    <Button
                      title="点击授权"
                      size="sm"
                      onPress={async () => {
                        if (
                          [RESULTS.UNAVAILABLE, RESULTS.GRANTED].includes(
                            item.powerStr,
                          )
                        ) {
                          return;
                        }
                        let v = '';
                        let t1 = dayjs();
                        let t2;
                        try {
                          v = await request(PERMISSIONS.ANDROID[item.name]);
                          t2 = dayjs();
                        } catch (e) {
                          Alert.alert('操作失败', e.message);
                          return;
                        }
                        let useMs = t2.diff(t1, 'ms');
                        if (useMs < CkPowerWaitMs && v !== RESULTS.GRANTED) {
                          setModalVisible(false);
                          openSettings().catch(() =>
                            Alert.alert('操作失败', '打开系统设置'),
                          );
                        } else {
                          setInfo();
                        }
                      }}
                    />
                    <Text style={style.remark}>{item.powerStr}</Text>
                  </View>
                </ListItem>
              ))}
            </View>
          ))}

          <View style={style.group}>
            {[...unavailablePowers].map((item, index) => (
              <ListItem key={index} style={{marginTop: 1}}>
                <ListItem.Content>
                  <ListItem.Title>{MapPowerName.get(item.name)}</ListItem.Title>
                  <Text style={style.remark}>{item.name}</Text>
                </ListItem.Content>

                <View>
                  <Text>{MapPowerResult.get(item.powerStr)}</Text>
                  <Text style={style.remark}>{item.powerStr}</Text>
                </View>
              </ListItem>
            ))}
          </View>

          <View style={style.group}>
            <View style={[style.item, style.itemNoBorder]}>
              <Text></Text>
              <Text></Text>
            </View>
          </View>
        </ScrollView>
      </View>
    </Modal>
  );
  const ChildrenCom = () => {
    return React.cloneElement(children, {
      ...otherProps,
      onPress: onPress,
    });
  };

  if (allowPowers.length !== clickPowers.length) {
    return (
      <>
        <ChildrenCom />
        <ModalBox />
      </>
    );
  }

  return React.cloneElement(children, {...otherProps});
};
